package com.qf.book.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//连库工具类
//四个与事务相关的方法
public class DBUtils {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;
    //创建线程本地局部变量
    public static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
    static {
        //1 加载配置文件

        try {
            Properties properties = new Properties();
            InputStream is = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
            properties.load(is);
            is.close();
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
    public static Connection getConnection(){
        try {
            Connection connection = threadLocal.get();
            if (connection == null){
                connection = DriverManager.getConnection(url,user,password);
                //绑定
                threadLocal.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            System.out.println("获取连接失败" +e.getMessage());
        }
        return null;
    }
    public static void closeAll(ResultSet rs, Statement stmt,Connection conn){
        try {
            if ( rs != null){
                rs.close();
            }
            if (stmt != null){
                stmt.close();
            }
            if (conn != null){
                if (conn.getAutoCommit()){
                    conn.close();
                    //解绑
                    threadLocal.remove();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static  void begin() throws SQLException{
        Connection connection = getConnection();
        if (connection != null){
            connection.setAutoCommit(false);
        }
    }
    public static  void commit() throws SQLException {
        Connection connection = getConnection();
        if (connection != null) {
            connection.commit();
        }
    }
    public static  void rollback()throws SQLException{
        Connection connection = getConnection();
        if (connection != null){
            connection.rollback();
        }
    }
    public static  void close()throws SQLException{
        Connection connection = getConnection();
        if (connection != null){
            connection.close();
            threadLocal.remove();
        }
    }

    public static void main(String[] args) {
        System.out.println(getConnection());
    }
}
